package com.ruoyi.common.utils.bean;

import java.io.*;

/**
 * @Classname ObjectCloneUtils
 * @Author: sunluquan
 * @Date: 2021/12/7 10:42
 * @Description TODO
 * 对象克隆工具类
 */
public class ObjectCloneUtils {

    /**
     * 深度克隆  通过序列化和反序列化实现
     * 在{@link ObjectInputStream}源码中的 invokeReadResolve method中会通过反射获取
     * readResolveMethod = getInheritableMethod(
     *                         cl, "readResolve", null, Object.class);
     * @param obj 对象要求  必须实现 Serializable 接口 并且允许多例的
     * @return
     */
    public static <T> T depthClone(Object obj){
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            //写入进byteArrayOutPut中
            objectOutputStream.writeObject(obj);

            objectOutputStream.flush();
            objectOutputStream.close();
            //读取byteArray
            objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));

            return (T) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectInputStream!=null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
